package com.dmy.chat.server.netty.handler;

import com.dmy.chat.server.netty.UserChannelBind;
import com.dmy.chat.server.netty.UserEventHandler;
import com.dmy.chat.server.netty.executor.SimpleUserEventExecutor;
import com.dmy.chat.server.netty.executor.UserEventExecutor;
import com.dmy.chat.server.netty.command.UserEventCommand;
import com.dmy.chat.server.netty.command.factory.UserEventCommandFactory;
import com.dmy.chat.server.netty.message.Messages;
import io.netty.channel.Channel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * create by YCQ for 2020/1/15 10:22
 */
public class DefaultUserEventHandler implements UserEventHandler {
    private static final Map<Object,DefaultUserEventHandler> CACHE_INSTANCE = new ConcurrentHashMap<>();

    private final UserChannelBind channelBind;
    private final UserEventExecutor executor;
    private final UserEventCommandFactory userEventCommandFactory;

    private DefaultUserEventHandler(UserChannelBind userChannelBind) {
        channelBind = userChannelBind;
        executor = new SimpleUserEventExecutor();
        userEventCommandFactory = new UserEventCommandFactory();
    }
    public static  DefaultUserEventHandler getInstance(UserChannelBind channelBind,Object key){
        return CACHE_INSTANCE.computeIfAbsent(key, k -> new DefaultUserEventHandler(channelBind));
    }
    public static DefaultUserEventHandler getInstance(UserChannelBind channelBind){
        return getInstance(channelBind,DefaultUserEventHandler.class);
    }

    @Override
    public void handler(Channel channel, Messages messages) {
        UserEventCommand command = userEventCommandFactory.getCommand(channelBind,channel,messages);
        executor.execute(command);
    }
}
